using System;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace DartsDetector.Classes
{
	public static class Utils
	{
		public static Control GetControlRecursive(string Name, Control Parent)
		{
			Control[] ctrls = Parent.Controls.Find(Name, true);
			if (ctrls.Length > 0)
				return ctrls[0];
			else
				return null;
		}


		public struct PointD
		{
			public double X
			{ get; set; }
			public double Y
			{ get; set; }
		}

		
		
		//Original
		//http://stackoverflow.com/questions/385305/efficient-maths-algorithm-to-calculate-intersections
		/// <summary>
		/// Find the intersection point between two lines.
		/// </summary>
		/// <param name="IntersectPoint">The intersection point.</param>
		/// <param name="L1StartPoint">The starting point of first line.</param>
		/// <param name="L1EndPoint">The end point of first line.</param>
		/// <param name="L2StartPoint">The starting point of second line.</param>
		/// <param name="L2EndPoint">The end point of second line.</param>		
		/// <returns>Returns a boolean. True if there is intersection, false otherwise.</returns>
		/// <remarks>The formula is taken from comp.graphics.algorithms Frequently Asked Questions.</remarks>
		public static bool LineIntersect(out Point IntersectPoint, Point L1StartPoint, Point L1EndPoint, Point L2StartPoint, Point L2EndPoint)//, out double L1IntersectPos, out double L2IntersectPos)
		{
			IntersectPoint = new Point();
			double ay_cy, ax_cx, px, py;
			double dx_cx = L2EndPoint.X - L2StartPoint.X,
					dy_cy = L2EndPoint.Y - L2StartPoint.Y,
					bx_ax = L1EndPoint.X - L1StartPoint.X,
					by_ay = L1EndPoint.Y - L1StartPoint.Y;

			double de = (bx_ax) * (dy_cy) - (by_ay) * (dx_cx);
			//double tor = 1.0E-10;         //tolerance


			if (Math.Abs(de) < 0.01)
				return false;
			//if (de > -tor && de < tor) return false; //line is in parallel

			ax_cx = L1StartPoint.X - L2StartPoint.X;
			ay_cy = L1StartPoint.Y - L2StartPoint.Y;
			double r = ((ay_cy) * (dx_cx) - (ax_cx) * (dy_cy)) / de;
			double s = ((ay_cy) * (bx_ax) - (ax_cx) * (by_ay)) / de;
			px = L1StartPoint.X + r * (bx_ax);
			py = L1StartPoint.Y + r * (by_ay);

			IntersectPoint.X = (int)px;  //return the intersection point
			IntersectPoint.Y = (int)py;  //return the intersection position
			
			return true; //indicate there is intersection
		}

	}


}
